/*
 * Copyright(C) 2019 FUYUN DATA SERVICES CO.,LTD. - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * 该源代码版权归属福韵数据服务有限公司所有
 * 未经授权，任何人不得复制、泄露、转载、使用，否则将视为侵权
 *
 */
import { message } from 'antd';

import * as React from 'react';
import { Route } from 'react-router-dom';
import { isArray } from 'util';
import NotFound from '../../pages/NotFound';
import { getAuthority } from '../../utils/authority';
import { defaultAuthority } from '../../config/base';

interface IProps extends React.Props<any> {
  key: any;
  exact?: boolean;
  path?: string;
  component: any;
  authority?: string[] | string;
}

message.config({
  maxCount: 1
});

// 类型保护 页面如果没有设置权限，则使用默认权限，默认权限为null的话，则默认不设权限
function f(sn: string | string[] | undefined): string | string[] {
  return sn || (defaultAuthority === null ? 'noAuthority' : defaultAuthority);
}
class Authorized extends React.Component<IProps, any> {
  public render() {
    // 获取用户权限
    let userAuthority: string[] | string = getAuthority();
    // 是否有权限查看页面的开关
    let isShow = false;
    // 获取页面权限
    let authority: string | string[] = f(this.props.authority);
    if (authority === 'noAuthority') {
      isShow = true;
    } else {
      // 格式化用户和页面权限,方便比对
      if (!isArray(userAuthority)) {
        if (userAuthority.indexOf(',') === -1) {
          userAuthority = [userAuthority];
        } else {
          userAuthority = userAuthority.split(',');
        }
      }
      if (!isArray(authority)) {
        if (authority.indexOf(',') === -1) {
          authority = [authority];
        } else {
          authority = authority.split(',');
        }
      }
      // 比对用户和页面的权限,决定是否有权查看页面
      if (isArray(userAuthority) && isArray(authority)) {
        userAuthority.forEach(item => {
          for (const ele of authority) {
            if (item === ele) {
              isShow = true;
            }
          }
        });
      }
    }
    return (
      <Route
        key={this.props.key}
        exact={this.props.exact === undefined ? false : true}
        path={this.props.path}
        component={isShow ? this.props.component : NotFound}
      />
    );
  }
}

export default Authorized;
